if (app.documents.length === 0) {
    alert("请打开一个文档。");
} else {
    var doc = app.activeDocument;
    var totalUngrouped = 0;

    function ungroupAll(doc) {
        var round = 0;
        while (doc.groups.length > 0) {
            round++;
            var countThisRound = doc.groups.length;
            for (var i = countThisRound - 1; i >= 0; i--) {
                try {
                    doc.groups[i].ungroup();
                } catch (e) {
                    $.writeln("取消编组失败: " + e);
                }
            }
            totalUngrouped += countThisRound;
            $.writeln("第 " + round + " 轮：取消了 " + countThisRound + " 个组");
        }
    }

    app.doScript(function() {
        app.scriptPreferences.enableRedraw = false;
        ungroupAll(doc);
        app.scriptPreferences.enableRedraw = true;
    }, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "取消所有组");

    alert("已取消所有组，共取消 " + totalUngrouped + " 个。");
}
